package edu.ynu.hhy.architectureclass.service;

import edu.ynu.hhy.architectureclass.dao.CameraDataDao;
import edu.ynu.hhy.architectureclass.entity.CameraData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;

@Service
public class CameraDataService {

    @Autowired
    private CameraDataDao cameraDataDao;
    @Autowired
    private RestTemplate restTemplate;

    public CameraData captureAndSaveCameraImage(String deviceSerial, String accessToken) {
        String url = "https://open.ys7.com/api/lapp/device/capture";

        // 构造请求体
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("accessToken", accessToken);
        requestBody.add("deviceSerial", deviceSerial);
        requestBody.add("channelNo", "1"); // 通道号传递1即可
        requestBody.add("quality", "1"); // 1-高清(720P)

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                if (responseBody.containsKey("data")) {
                    Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                    String picUrl = (String) data.get("picUrl");

                    // 创建并保存 CameraData 对象
                    CameraData cameraData = new CameraData();
                    cameraData.setDeviceSerial(deviceSerial);
                    cameraData.setPicUrl(picUrl); // 保存图片的URL
                    cameraData.setCreateTime(new Date()); // 设置创建时间

                    return cameraDataDao.save(cameraData);
                } else {
                    System.err.println("API response does not contain 'data' field");
                }
            } else {
                System.err.println("API call failed with status code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            System.err.println("Failed to fetch camera data for device: " + deviceSerial);
            e.printStackTrace();
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException httpException = (HttpClientErrorException) e;
                System.err.println("HTTP Status Code: " + httpException.getStatusCode());
                System.err.println("Response Body: " + httpException.getResponseBodyAsString());
            }
        }

        return null;
    }
}